package com.dzl.integral.service.impl;

import com.dzl.base.service.BaseServiceImpl;
import com.dzl.config.exception.CommonException;
import com.dzl.enterprise.service.WelfareEnterpriseService;
import com.dzl.fee.pojo.WelfareFeeOrder;
import com.dzl.fee.service.WelfareFeeOrderService;
import com.dzl.integral.dao.WelfareIntegralRecordMapper;
import com.dzl.integral.pojo.WelfareIntegralProcess;
import com.dzl.integral.pojo.WelfareIntegralRecord;
import com.dzl.integral.pojo.dto.WelfareIntegralProcessDto;
import com.dzl.integral.pojo.dto.WelfareIntegralRechargeDto;
import com.dzl.integral.pojo.query.WelfareIntegralRecordQuery;
import com.dzl.integral.pojo.vo.WelfareIntegralRecordVo;
import com.dzl.integral.service.WelfareIntegralProcessService;
import com.dzl.integral.service.WelfareIntegralRecordService;
import com.dzl.util.RedisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 积分充值审核表(WelfareIntegralRecord)表服务实现类
 *
 * @author wangjian
 * @date 2021-09-06 15:12:45
 */
@Service
public class WelfareIntegralRecordServiceImpl extends BaseServiceImpl<WelfareIntegralRecord> implements WelfareIntegralRecordService {

    @Autowired
    private WelfareIntegralRecordMapper mapper;
    @Autowired
    private WelfareFeeOrderService welfareFeeOrderService;
    @Autowired
    private WelfareIntegralProcessService welfareIntegralProcessService;
    @Autowired
    private WelfareEnterpriseService welfareEnterpriseService;

    @Override
    public PageInfo<WelfareIntegralRecordVo> selectIntegralRecordListPage(WelfareIntegralRecordQuery welfareIntegralRecordQuery) {
        PageHelper.startPage(welfareIntegralRecordQuery);
        List<WelfareIntegralRecordVo> list = mapper.selectIntegralRecordList(welfareIntegralRecordQuery);
        PageInfo<WelfareIntegralRecordVo> page = new PageInfo<WelfareIntegralRecordVo>(list);
        return page;
    }

    @Override
    public List<WelfareIntegralRecordVo> selectIntegralRecordNoGrantOrIsGrantButHasIntegralList(WelfareIntegralRecordQuery welfareIntegralRecordQuery) {
        return mapper.selectIntegralRecordNoGrantOrIsGrantButHasIntegralList(welfareIntegralRecordQuery);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveIntegralRecharge(WelfareIntegralRechargeDto dto,String createName) {
        //添加业务员订单 得到业务员订单ID
        WelfareFeeOrder welfareFeeOrder = new WelfareFeeOrder();
        welfareFeeOrder.setSalesUserId(dto.getSalesUserId());
        welfareFeeOrder.setEnterpriseId(dto.getEnterpriseId());
        welfareFeeOrder.setOrderType(3);
        welfareFeeOrder.setIntegralAmount(dto.getRechargeIntegral());
        welfareFeeOrder.setStatus(1);
        welfareFeeOrder.setCreaterName(createName);
        welfareFeeOrder.setCreateTime(new Date());
        welfareFeeOrderService.insertSelective(welfareFeeOrder);
        //添加充值记录
        WelfareIntegralRecord welfareIntegralRecord = new WelfareIntegralRecord();
        welfareIntegralRecord.setCreateName(createName);
        welfareIntegralRecord.setCreateTime(new Date());
        //设置到账时间为充值时间后两个小时
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.HOUR_OF_DAY,+2);
        welfareIntegralRecord.setSuccessTime(cal.getTime());
        welfareIntegralRecord.setRechargeIntegral(dto.getRechargeIntegral());
        welfareIntegralRecord.setStatus(1);
        welfareIntegralRecord.setFeeOrderId(welfareFeeOrder.getId());
        mapper.insertSelective(welfareIntegralRecord);
        //添加审核进度记录
        WelfareIntegralProcess welfareIntegralProcess = new WelfareIntegralProcess();
        welfareIntegralProcess.setCreateTime(new Date());
        welfareIntegralProcess.setCreateName(createName);
        welfareIntegralProcess.setIntegralRecordId(welfareIntegralRecord.getId());
        welfareIntegralProcess.setStatus(1);
        welfareIntegralProcessService.insertSelective(welfareIntegralProcess);
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveIntegralProcess(WelfareIntegralProcessDto dto) {
        //修改积分充值记录的状态
        WelfareIntegralRecord welfareIntegralRecord = new WelfareIntegralRecord();
        welfareIntegralRecord.setId(dto.getIntegralRecordId());
        welfareIntegralRecord.setStatus(dto.getRechargeStatus());
        welfareIntegralRecord.setUpdateTime(new Date());
        mapper.updateByPrimaryKeySelective(welfareIntegralRecord);
        welfareIntegralProcessService.insertSelective(dto);
        //撤回充值的积分
        if (dto.getStatus() == 5 ){
            WelfareIntegralRecord record = mapper.selectByPrimaryKey(dto.getIntegralRecordId());
            //调用公司充值积分方法
            WelfareFeeOrder welfareFeeOrder = welfareFeeOrderService.selectByPrimaryKey(record.getFeeOrderId());
            welfareEnterpriseService.saveEnterpriseIntegral(welfareFeeOrder.getEnterpriseId(),record.getRechargeIntegral().negate());
        }
        if (dto.getStatus() == 3 || dto.getStatus() == 4 || dto.getStatus() == 5){
            //取消生成的业务员订单
            WelfareIntegralRecord select = mapper.selectByPrimaryKey(dto.getIntegralRecordId());
            WelfareFeeOrder welfareFeeOrder = welfareFeeOrderService.selectByPrimaryKey(select.getFeeOrderId());
            welfareFeeOrder.setStatus(0);
            welfareFeeOrderService.updateByPrimaryKeySelective(welfareFeeOrder);
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer integralRechargeSuccess() {
        String key = "integralRechargeSuccess";
        RLock rLock = RedisUtil.lock(key);
        try {
            if (rLock.tryLock(15, TimeUnit.SECONDS)) {
                //查询出满足自动到账要求的充值记录
                List<WelfareIntegralRecordVo> list = mapper.selectIntegralRechargeSuccessList();
                for (WelfareIntegralRecordVo welfareIntegralRecord : list){
                    //调用公司充值积分方法
                    Integer i = welfareEnterpriseService.saveEnterpriseIntegral(welfareIntegralRecord.getEnterpriseId(), welfareIntegralRecord.getRechargeIntegral());
                    //修改记录表的充值状态
                    if (i.equals(1)){
                        //到账
                        welfareIntegralRecord.setStatus(3);
                        mapper.updateByPrimaryKeySelective(welfareIntegralRecord);
                    }else {
                        //失败  原因是充值金额过大，超过公司限定的余额
                        welfareIntegralRecord.setStatus(4);
                        mapper.updateByPrimaryKeySelective(welfareIntegralRecord);
                        //取消生成的业务员订单
                        WelfareFeeOrder welfareFeeOrder = welfareFeeOrderService.selectByPrimaryKey(welfareIntegralRecord.getFeeOrderId());
                        welfareFeeOrder.setStatus(0);
                        welfareFeeOrderService.updateByPrimaryKeySelective(welfareFeeOrder);
                        //记录操作
                        WelfareIntegralProcess welfareIntegralProcess = new WelfareIntegralProcess();
                        welfareIntegralProcess.setStatus(4);
                        welfareIntegralProcess.setIntegralRecordId(welfareIntegralRecord.getId());
                        welfareIntegralProcess.setCreateTime(new Date());
                        welfareIntegralProcess.setCreateName("系统");
                        welfareIntegralProcess.setReason("充值金额过大，导致该公司的账户积分超出限额");
                        welfareIntegralProcessService.insertSelective(welfareIntegralProcess);
                    }

                }
                return list.size();
            }
        }catch (Exception e) {
            throw new CommonException(e.getMessage());
        } finally {
            if (rLock.isHeldByCurrentThread()) {
                rLock.unlock();
            }
        }
        return null;
    }

    @Override
    public List<Integer> selectIntegralRecordCount(WelfareIntegralRecordQuery welfareIntegralRecordQuery) {
        return mapper.selectIntegralRecordCount(welfareIntegralRecordQuery);
    }
}